package com.example.last.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.last.common.Constants;
import com.example.last.common.enums.RoleEnum;
import com.example.last.entity.Account;
import com.example.last.service.AdminService;
import com.example.last.service.DoctorService;
import com.example.last.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class JwtTokenUtils {
    private static AdminService staticAdminService;
    private static DoctorService staticDoctorService;
    private static UserService staticUserService;
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private AdminService adminService;
    @Resource
    private DoctorService doctorService;
    @Resource
    private UserService userService;

    @PostConstruct
    public void init() {
        staticAdminService = adminService;
        staticDoctorService = doctorService;
        staticUserService = userService;
    }


    /**
     * 生成token
     */
    public static String genToken(String data, String sign) {
        return JWT.create()
                .withAudience(data) // 将user_id保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),  1)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     */

    public static Account getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null) {
            log.error("Request is null");
            return null;
        }
        String token = request.getHeader(Constants.TOKEN);
        if (token == null) {
            log.info("Token from header is missing");
            return null;
        }

        try {
            String audience = JWT.decode(token).getAudience().get(0);
            String[] userRole = audience.split("-");
            Integer userId = Integer.valueOf(userRole[0]);
            String role = userRole[1];
            log.info("Retrieving user info for userId: {} and role: {}",userId,role);

            if(RoleEnum.ADMIN.name().equals(role)) {
                Account admin =  staticAdminService.findById(userId);
                if(admin == null) {
                    log.warn("No admin found for userId: {}", userId);
                }
                return admin;
            }
            if(RoleEnum.DOCTOR.name().equals(role)) {
                Account doctor =  staticDoctorService.findById(userId);
                if(doctor == null ) {
                    log.warn("No doctor found for userId: {}", userId);
                }
                return doctor;
            }
            if(RoleEnum.USER.name().equals(role)) {
                Account user = staticUserService.findById(userId);
                if(user == null) {
                    log.warn("No user found for userId: {}", userId);
                }
                return user;
            }
        } catch (Exception e) {
            log.error("Error occurred while getting current user from JWT Token", e);
        }
        return null;
    }


}
